/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package IFSv2.Forms.Utilities;

import IFSv2.Connection.DBConnection;
import java.awt.Toolkit;
import java.awt.event.KeyEvent;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;

/**
 *
 * @author Joel
 */
public class frmFind extends javax.swing.JDialog {

    private javax.swing.table.DefaultTableModel table;
    private String tableName;
    private String selectedID;
    private String selectedPrimaryID;
    private String _sqlCmd;
    private String refColumn;
    private String PrimaryKey;
    private int numOfCols;
    
    
    
    public frmFind(java.awt.Frame parent, boolean modal, String tableName, String refColumn, String PrimaryKey) {
        super(parent, modal);
        //for find
        setIconImage(Toolkit.getDefaultToolkit().getImage(this.getClass().getResource("/IFSv2/Images/timlogo.png")));
        this.refColumn = refColumn;        
        this.PrimaryKey = PrimaryKey;        
        this.tableName = tableName;
        this.setLocationRelativeTo(null);
        selectedID = "";
        selectedPrimaryID = "";
        initComponents();
        getTableColumns();
        searchTbx.requestFocus();
    }

    public frmFind(java.awt.Frame parent, boolean modal, String tableName, String refColumnID, String keyword, String PrimaryKey) {
        
        this(parent, modal, tableName, refColumnID, PrimaryKey);

        searchTbx.setText(keyword);
        updateTable(keyword);
        
    }
    
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        columnCombo = new javax.swing.JComboBox();
        searchTbx = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jTable1.setAutoCreateRowSorter(true);
        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {

            }

        ){
            public boolean isCellEditable(int row, int column){
                return false;
            }

        });
        jTable1.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
        jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTable1MouseClicked(evt);
            }
        });
        jTable1.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jTable1KeyPressed(evt);
            }
        });
        jScrollPane1.setViewportView(jTable1);

        searchTbx.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                searchTbxKeyPressed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(columnCombo, javax.swing.GroupLayout.PREFERRED_SIZE, 149, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(searchTbx, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 75, Short.MAX_VALUE))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(columnCombo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(searchTbx, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 252, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable1MouseClicked
        if (evt.getClickCount() == 2) {
            getCurrentRow();
        }
    }//GEN-LAST:event_jTable1MouseClicked

    private void jTable1KeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTable1KeyPressed
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
            getCurrentRow();
        }
    }//GEN-LAST:event_jTable1KeyPressed

    private void searchTbxKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_searchTbxKeyPressed
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
            getSearchTFValue();
        }
    }//GEN-LAST:event_searchTbxKeyPressed

    private void getTableColumns(){

        table = (javax.swing.table.DefaultTableModel) jTable1.getModel();
        _sqlCmd = "SELECT * FROM " + tableName;
        try {
            final ResultSet rsTableCol = DBConnection.getActiveConnection().createStatement().executeQuery(_sqlCmd + " LIMIT 1");
            final ResultSetMetaData rsmdTableCol = rsTableCol.getMetaData();
            numOfCols = rsmdTableCol.getColumnCount();
            for(int i=1; i< numOfCols; i++){
                table.addColumn(rsmdTableCol.getColumnName(i));
                columnCombo.addItem(rsmdTableCol.getColumnName(i));
            }
            columnCombo.setSelectedItem(refColumn);
            rsTableCol.close();
        } catch (SQLException ex) {
            Logger.getLogger(frmFind.class.getName()).log(Level.SEVERE, null, ex);
        } 

    }
    
    private void updateTable(String searchText){
        String _sqlCmd;
        if(searchText != null)
            _sqlCmd = this._sqlCmd + " WHERE "+columnCombo.getSelectedItem()+" LIKE '%"+searchText+"%'";
        else 
            _sqlCmd = this._sqlCmd;
        jTable1.setSurrendersFocusOnKeystroke(true);
        table = (javax.swing.table.DefaultTableModel) jTable1.getModel();  
        
        try{
            table.setRowCount(0);
        }catch(Exception e){}
        
        try {
            ResultSet rs = DBConnection.getActiveConnection().createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY).executeQuery(_sqlCmd);
            while (rs.next()){
                Object[] data = new Object[numOfCols];
                for(int i=0; i<data.length; i++){
                    data[i] = rs.getObject(i+1);
                }
                table.addRow(data);
            }
            table.fireTableDataChanged();
            
            
        } catch (SQLException ex) {
            Logger.getLogger(frmFind.class.getName()).log(Level.SEVERE, null, ex);
        } 
    }
    
    private void getCurrentRow(){
        selectedID = table.getValueAt(jTable1.getSelectedRow(), table.findColumn(refColumn)).toString();
        selectedPrimaryID = table.getValueAt(jTable1.getSelectedRow(), table.findColumn(PrimaryKey)).toString();
        frmFind.this.dispose();
    }
    
    public String getSelectedID(){
        return this.selectedID;
    }
    
    public String getSelectedPrimaryID(){
        return this.selectedPrimaryID;
    }

    private void getSearchTFValue() {
        String searchText;
        
        if (searchTbx.getText().isEmpty()){
            final int result = JOptionPane.showConfirmDialog(null,"You did not provide a parameter. This may take a while. \nDo you want to Continue?","",JOptionPane.YES_NO_OPTION);
            if(result == JOptionPane.YES_OPTION){
                updateTable(searchTbx.getText());
                jTable1.requestFocus();
            }
        }else{
           searchText = searchTbx.getText().trim();
           updateTable(searchText);
        }
    }
    
    
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JComboBox columnCombo;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextField searchTbx;
    // End of variables declaration//GEN-END:variables
}
